import loadMark from './loadMark';
import { monitorDom } from './util';
import { DEFAULT_SETTINGS } from './constants';

let waterobserver;
/*加载水印-添加浏览器窗口监听事件-添加dom变化监听事件*/
export function watermark(settings = {}) {
  //这一步防止重复调用渲染
  waterobserver && waterobserver.disconnect();

  loadMark(settings)

  const resizeFunction = function() {
    loadMark(settings)
  };
  // 取消浏览器窗口监听事件
  window.removeEventListener('resize', resizeFunction);
  // 添加浏览器窗口监听事件
  window.addEventListener('resize', resizeFunction);
  const watermarkId = settings.id || DEFAULT_SETTINGS.id;
  const watermarkParentSelector = settings.parentSelector || DEFAULT_SETTINGS.parentSelector;
  // 添加dom变化监听事件
  const isSupportMutationObserve = monitorDom(watermarkParentSelector, (mutations, observer) => {
    waterobserver = observer;
    // 当节点被删除
    if (mutations[0].removedNodes[0] && mutations[0].removedNodes[0].id === watermarkId) {
      loadMark(settings)
    }
    //当样式被修改
    if (mutations[0].attributeName == 'style' && mutations[0].target.id === watermarkId) {
      document.querySelector('#' + watermarkId).remove();
      // loadMark(settings);
    }
    //当id被修改
    if (mutations[0].attributeName == 'id' && mutations[0].oldValue === watermarkId) {
      mutations[0].target.remove();
      // loadMark(settings);
    }
    //子节点被删除,防止把子节点移走
    if (
      mutations[0].nextSibling &&
      mutations[0].nextSibling.id === watermarkId &&
      mutations[0].removedNodes[0]
    ) {
      mutations[0].removedNodes[0].remove();
      document
        .querySelector(watermarkParentSelector)
        .insertBefore(mutations[0].removedNodes[0], document.querySelector('#' + watermarkId));
    }
  });
  // 不支持MutationObserve时的降级方案Mutation Events
  // if (!isSupportMutationObserve) {
  //   observeNode.addEventListener(
  //     'DOMNodeRemoved',
  //     function() {
  //       loadMark(settings);
  //     },
  //     false
  //   );
  // }
  loadMark(settings);
}
